<template>
  <div class="app-container customer-div">
    <el-menu :default-active="listQuery.tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="waitMyCheck">待处理</el-menu-item>
      <el-menu-item index="my">我的</el-menu-item>
      <el-menu-item index="all" v-if="allDeliverFreightSettlement">全部</el-menu-item>
    </el-menu>
    <div style="margin-top: 40px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
        <el-form-item label="单据类型：">
          <el-select v-model="listQuery.billType" filterable placeholder="请选择" clearable>
            <el-option :value="0" label="发货单" :key="0">发货单</el-option>
            <el-option :value="1" label="入库单" :key="1">入库单</el-option>
            <el-option :value="2" label="其它单据" :key="2">其它单据</el-option>
            <el-option :value="3" label="采购发货单" :key="3">采购发货单</el-option>
            <el-option :value="4" label="外贸发货单" :key="4">外贸发货单</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关键字：">
          <el-input v-model="listQuery.keywords" placeholder="结算单号/收款方"></el-input>
        </el-form-item>
        <el-form-item label="创建日期：">
          <el-date-picker
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="listQuery.createdAt"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="listQuery.settlementState" filterable placeholder="请选择" clearable>
            <el-option :value="item.key" :label="item.name" :key="item.name" v-for="item in stateList"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作人：" v-if="listQuery.tab == 'all'">
          <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
                  @click="handleSearchList()"
                  type="primary">
            查询
          </el-button>
          <el-button
                  @click="toAddSettlement('add',null)"
                  type="primary">
            新增
          </el-button>
          <el-button
            v-if="listQuery.tab == 'all'"
            :loading="btnLoading"
            @click="downloadExcel"
            type="primary">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--数据列表-->
    <div class="table-container">
      <el-table
              v-loading="listLoading"
              :data="tableData"
              border
              style="width: 100%; margin-top: 20px">
        <el-table-column
                align="center"
                label="收款方"
                width="150">
          <template slot-scope="scope">
            {{scope.row.receivingCustomerName}}
          </template>
        </el-table-column>
        <el-table-column
                align="center"
                label="单据类型"
                width="100">
          <template slot-scope="scope">
            {{scope.row.billType | fiferType}}
          </template>
        </el-table-column>
        <el-table-column
                align="center"
                label="单据数量"
                width="100">
          <template slot-scope="scope">
            {{scope.row.deliverIdsNum}}
          </template>
        </el-table-column>
        <el-table-column
                label="运费结算金额"
                width="120"
                align="center">
          <template slot-scope="scope">
            {{scope.row.sumAmount}}
          </template>
        </el-table-column>
        <el-table-column
                align="center"
                prop="settlementAmount"
                label="实际结算金额"
                width="120">
        </el-table-column>
        <el-table-column
                label="付款方式"
                width="100"
                align="center">
          <template slot-scope="scope">
            {{scope.row.payType | fiferPayState}}
          </template>
        </el-table-column>
        <el-table-column
                label="备注">
          <template slot-scope="scope">
            {{scope.row.remark}}
          </template>
        </el-table-column>
        <el-table-column
                label="添加日期"
                width="150"
                align="center">
          <template slot-scope="scope">
            {{scope.row.createdAt}}
          </template>
        </el-table-column>
        <el-table-column
                align="center"
                label="操作人"
                width="100">
          <template slot-scope="scope">
            {{scope.row.username}}
          </template>
        </el-table-column>
        <el-table-column
                align="center"
                label="付款日期"
                width="100">
          <template slot-scope="scope">
            {{scope.row.payDate}}
          </template>
        </el-table-column>
        <el-table-column
                align="center"
                label="付款人"
                width="100">
          <template slot-scope="scope">
            {{scope.row.payUsername}}
          </template>
        </el-table-column>
        <el-table-column
                align="center"
                label="状态"
                width="100">
          <template slot-scope="scope">
            {{scope.row.deliverStateStr}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="费用承担"
          width="100">
          <template slot-scope="scope">
                {{scope.row.freightUserName}}
          </template>
        </el-table-column>
        <el-table-column
                fixed="right"
                label="操作"
                align="center">
          <template slot-scope="scope">
<!--            <el-button-->
<!--                    v-if="scope.row.settlementState == 0 && scope.row.isNeedMyCheck ==1"-->
<!--                    type="text"-->
<!--                    size="mini"-->
<!--                    @click="toAddSettlement('edit',scope.row)">编辑-->
<!--            </el-button>-->
            <el-button
                    v-if="scope.row.settlementState == 30 && scope.row.isNeedMyCheck ==1"
                    type="text"
                    size="mini"
                    @click="bossCheck(scope.row)">审批
            </el-button>
            <el-button
                    v-if="scope.row.settlementState == 30 && scope.row.isNeedMyCheck ==1"
                    type="text"
                    size="mini"
                    @click="showCancel(scope.row)">回退
            </el-button>
            <el-button
                    type="text"
                    size="mini"
                    @click="toInfo(scope.row)">查看
            </el-button>
            <el-button
                    v-if="(scope.row.settlementState != 10 && scope.row.settlementState != 50) && scope.row.userId == userId"
                    type="text"
                    size="mini"
                    @click="delDate(scope.row)">取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              layout="total, sizes,prev, pager, next,jumper"
              :current-page.sync="listQuery.pageNum"
              :page-size="listQuery.pageSize"
              :page-sizes="[10,15,20]"
              :total="count">
      </el-pagination>
    </div>

    <!--回退弹窗-->
    <el-dialog
            :close-on-click-modal="false"
            title="审核回退"
            :visible.sync="dialogVisible2"
            width="500px">
      <el-form :model="passForm" size="mini" label-width="100px" ref="passForm" :rules="rules2">
        <el-form-item label="备注信息：" prop="remark">
          <el-input :autosize="{ minRows: 2, maxRows: 6}" type="textarea" v-model="passForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button  @click="dialogVisible2 = false">取消</el-button>
          <el-button @click="shenheBack" :loading="btnLoading2" type="primary">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
    import {settlementPay,freightSettlement,getQiniuToken,settlementDetailList,settlementExportDetailList,settlementMove,uploadBase64,deleteSettlement,settlementProcess,getOrderUsersList} from '@/api/partner'
    import store from '@/store'
    import { mapGetters } from 'vuex'
    const defaultListQuery={
      keywords:'',
      createdAt:null,
      pageNum: 1,
      pageSize: 10,
      settlementState:null,
      billType:null,
      userId:'',
      tab:'waitMyCheck'
    };
    const defaultListQuery2={
      settlementNo:'',
      receivingCustomerName:null,
      settlementDate:null,
      deliverSn:null,
      isDelete:'',
      pageNum: 1,
      pageSize: 10,
    };
    const defaultPriceForm={
      orderId:'',
      payAccount : '',
      payType:'银行汇款',
      payAmount:'',
      payContent:'',
      remark:'',
      unPaidAmount:''
    };
  const defaultSendForm={
    settlementId: '',
    files: [],
    payRemark: '',
    payDate:'',
    filesSrc:null,
  };
    export default {
      name: "index",
      data(){
          return {
              listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
              tableData: [],
              count: 0,
              listLoading: false,
              roles:store.getters.roles ? store.getters.roles : [],
              stateList:[
                      {key:0,name:'待申请人确认'},
                      {key:10,name:'已作废'},
                      {key:20,name:'待财务确认'},
                      {key:30,name:'待总经理审核'},
                      {key:40,name:'待支付'},
                      {key:50,name:'已支付'},
                      ],
              btnLoading2:false,
              dialogVisible2:false,
              passForm:{
                remark:'',
              },
              rules2:{
                remark:[{required: true, trigger: 'blur' ,message: '请输入回退原因',}],
              },
            btnLoading:false,
            userOptionList:[]

          }
      },
      computed: {
        ...mapGetters([
          'name',
          'mobile',
          'userId'
        ]),
        isCanCustomerByAll(){
          if(this.roles.indexOf("customerByAll") != -1){
            return true
          }else{
            return false
          }
        },
        allDeliverFreightSettlement(){
          if(this.roles.indexOf("allDeliverFreightSettlement") != -1){
            return true
          }else{
            return false
          }
        }
      },
      created() {
        this.getList();
        this.getUserOptionList()
      },
      filters: {
        fiferPayState(val){
          if(val == 1){
            return '银行汇款'
          }else if(val == 2){
            return '现金'
          }else if(val == 3){
            return '支付宝'
          }else if(val == 4){
            return '微信'
          }
        },
        fiferType(val){
          if(val == 0){
            return '发货单'
          }else if(val == 1){
            return '入库单'
          }else if(val == 2){
            return '其它单据'
          }else if(val == 3){
            return '采购发货单'
          }else if(val == 4){
            return '外贸发货单'
          }
        },
      },

      methods:{
        //获取报价人下拉选项
        getUserOptionList() {
          getOrderUsersList({status:1,departmentId:4}).then((res) => {
            this.userOptionList = res;
          });
        },
        //下载excle
        downloadExcel(){
          this.btnLoading = true
          let params = JSON.parse(JSON.stringify(this.listQuery));
          params.export = 1;
          delete params.pageSize;
          delete params.pageNum
          freightSettlement(params).then((res)=>{
            this.btnLoading = false
            require.ensure([], () => {
              const { export_json_to_excel } = require('sheet/Export2Excel');
              const tHeader = res.title;
              const filterVal = res.columns;
              const list = res.list;
              const data = this.formatJson(filterVal, list);
              export_json_to_excel(tHeader, data, res.fileName);
            })
          }).catch(()=>{})
        },

        //下载表格数据格式化
        formatJson(filterVal, jsonData) {
          return jsonData.map(v => filterVal.map(j => v[j]))
        },

        //老板审批
        bossCheck(item){
          settlementProcess({settlementId:item.settlementId ,action:'bossCheck'}).then((res)=>{
            this.getList();
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
          })
        },
        //显示回退弹窗
        showCancel(item){
          this.dialogVisible2 = true;
          this.passForm.remark = '',
          this.passForm.settlementId = item.settlementId;
        },

        //审核
        shenheBack(){
          let data = {};
            data.settlementId= this.passForm.settlementId;
            data.action = 'back';
            data.remark = this.passForm.remark;
            this.$refs.passForm.validate((valid) => {
              if (valid) {
                this.btnLoading2 = true;
                settlementProcess(data).then((res)=>{
                  this.dialogVisible2 = false;
                  this.btnLoading2 = false;
                  this.getList();
                  this.$message({
                    type: 'success',
                    message: '操作成功!'
                  });
                }).catch(()=>{
                  this.btnLoading2 = false;
                })
              }
            });
          },
        handleSelect(key){
          this.listQuery = JSON.parse(JSON.stringify(defaultListQuery))
          this.listQuery.tab = key;
          this.handleSearchList();
        },
        //取消
        delDate(item){
          this.$confirm('是否确定删除', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteSettlement({settlementId:item.settlementId,isDelete : 1}).then(()=>{
              this.dialogVisible = false;
              this.getList();
              this.$message({
                type: 'success',
                message: '操作成功!'
              });

            })

          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            });
          });
        },

        //去新增运费结算单页
        toAddSettlement(type,item){
          let routeData
          if(type == 'add'){
           routeData = this.$router.resolve({name:'deliverAddSettlement'});
          }else{
            routeData = this.$router.resolve({name:'deliverAddSettlement',query:{id:item.settlementId}});
          }
          window.open(routeData.href);
        },

        //去查看页
        toInfo(item){
          let routeData = this.$router.resolve({name:'deliverSettlementInfo',query:{id:item.settlementId}});
          window.open(routeData.href);
        },

        handleSizeChange(val){
          this.listQuery.pageNum = 1;
          this.listQuery.pageSize = val;
          this.getList();
        },
        handleCurrentChange(val){
          this.listQuery.pageNum = val;
          this.getList();
        },

        handleSearchList(){
          this.listQuery.pageNum = 1;
          this.getList();
        },

        //获取订单列表
        getList() {
          this.listLoading = true;
          freightSettlement(this.listQuery).then(response => {
            this.tableData = response.list;
            this.count = response.count;
            this.listLoading = false;
          }).catch(()=>{
            this.listLoading = false;
          });
        },

      },
    }
</script>

<style scoped lang="scss">
  .avatar-uploader{
    margin-bottom:10px;
    display: inline-block;
    width:80px;
    height:80px;
    border:1px solid #DCDFE6;
    text-align: center;
    line-height: 80px;
  }
</style>
